package com.ace3l.legal.backend.web;

import org.springframework.web.servlet.mvc.Controller;
import org.springframework.web.servlet.mvc.ServletForwardingController;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.InternalResourceView;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ace3l.legal.Constants;
import com.ace3l.legal.backend.domain.Role;

/**
 * Created by IntelliJ IDEA.
 * User: ageer
 * Date: Jul 26, 2008
 * Time: 6:53:04 AM
 * To change this template use File | Settings | File Templates.
 */
public class Ace3LGWTController implements Controller {
    public ModelAndView handleRequest(HttpServletRequest req, HttpServletResponse res) throws Exception {
        
        WebApplicationContext appCtx = WebApplicationContextUtils.getWebApplicationContext(req.getSession().getServletContext());
        String role = (String) req.getSession().getAttribute(Constants.USERROLE);
        if (role == null) role = Constants.NOAUTH;

        if (SimpleRequestParser.isModuleRequest(req.getPathInfo())) {
            String module = SimpleRequestParser.getModule(req.getPathInfo());

            if ((module.equals(Constants.HOMEPORTAL)) ||
                    (module.equals(Constants.ADMINPORTAL) && role.equals(Role.ADMIN)) ||
                    (module.equals(Constants.STUDENTPORTAL) && role.equals(Role.STUDENT)) ||
                    (module.equals(Constants.LAWFIRMPORTAL) && role.equals(Role.LAWFIRM)))
                return new ModelAndView(new InternalResourceView("/WEB-INF/gwt" + req.getPathInfo()));
        } else if (SimpleRequestParser.isServiceRequest(req.getPathInfo())) {
            String serviceRequested = req.getPathInfo().substring(1);
            if ( (serviceRequested.equals("StudentPortalService") && role.equals(Role.STUDENT)) ||
                 (serviceRequested.equals("LawFirmPortalService") && role.equals(Role.LAWFIRM)) ||
                 (serviceRequested.equals("AdminPortalService") && role.equals(Role.ADMIN)) ||
                 (serviceRequested.equals("UserService"))) {
                ServletForwardingController sfc = (ServletForwardingController) appCtx.getBean(serviceRequested);
                if (sfc != null) {
                    sfc.handleRequest(req, res);
                    return null;
                }
            }
        }
        return new ModelAndView(new InternalResourceView("/WEB-INF/error.jsp"));
    }
}
